import org.codehaus.groovy.grails.commons.*

class MailNotifierService {

  def mailService

  boolean transactional = true

  public sendDailyDigest() {
    def users = User.findAllByDailyDigest(true)
    if (users) sendDigest(users, 'Daily')
  }

  public sendWeeklyDigest() {
    def users = User.findAllByWeeklyDigest(true)
    if (users) sendDigest(users, 'Weekly')
  }


  public sendDigest (User user, String scope) {
    sendDigest([user], scope)
  }

  public sendTestMail(String receiver) {
    log.info "Sending testmail to ${receiver}"
    
    mailService.sendMail {
      to receiver
      from "info@motsangria.de"
      subject "Testmail from MoTSangria"
      body "Hi!\nThis is a testmail sent to you to check that your mail settings on the MoTSangria Homepage are correct.\n\nCheers\nThe MoTSangria Web Team"
    }
  }

  public sendDigest(List users, String scope) {

    def config = ConfigurationHolder.config    
    Date now = new Date()
    
    def receivers = []
    users.each {u ->
      log.debug ("Adding main mail address of user ${u} to receivers list")
      def emailAddress = u.emailAddresses.find {it.isMain == true}
      if (emailAddress) {
        receivers.add(emailAddress.email)
        log.debug ("Main mail address of user ${u} is ${emailAddress}")
      } else {
        log.info ("Main mail address of user ${u} not found")
      }
    }

    def messages = []
    if (scope == "Daily") {
      messages = Message.findAllByDateCreatedBetween(now-1, now)
    } else {
      messages = Message.findAllByDateCreatedBetween(now-7, now)
    }

    String bodyText = "Hi! \n This is the ${scope} MoTSangria activity report:\n \n -------------------\n \n" 
    messages.reverse().each {message ->
      def link = ""
      if (message.link) link = "(${message.link}')"
      def time = ""
      if (scope == "Daily") {
        time = DateTagLib.getTime(message.dateCreated)
      } else {
        time = DateTagLib.getShortDate(message.dateCreated)
      }
      bodyText = "$bodyText [${time}] ${message.user}: ${message.content} ${message.isPrivate ? '\n(MOTS only Message)' : ''}\n ${link}\n -------------------\n"
    }
    if (!bodyText) bodyText = "--- No activity ---\n"
    bodyText = "${bodyText}\n Find all updates at http://motsangria.morphexchange.com.\nCheers,\nThe MoTSangria Web Team"

    log.info "Sending ${scope} activity report to ${receivers}"
    
    mailService.sendMail {
      to "info@motsangria.de"
      bcc receivers.toArray(new String[receivers.size()])
      from "info@motsangria.de"
      subject "$scope MoTSangria Activity Report"
      body bodyText
    }
  }
}
